﻿using System.Net;

using WeDonekRpc.Client.Interface;
using WeDonekRpc.Client.Track.Config;
using WeDonekRpc.Client.Track.Model;

using WeDonekRpc.Helper;
using WeDonekRpc.Helper.Http;

namespace WeDonekRpc.Client.Track
{
    /// <summary>
    /// Zipkin链路记录器
    /// </summary>
    public class ZipkinTack : ITack
    {
        private readonly ZipkinConfig _Config = null;
        private readonly IDelayDataSave<TrackBody> _TackList = null;
        public ZipkinTack (ZipkinConfig config)
        {
            this._Config = config;
            this._TackList = new DelayDataSave<TrackBody>(new SaveDelayData<TrackBody>(this._Save), 15, 10);
        }

        private void _Save (ref TrackBody[] tracks)
        {
            string json = new ZipkinTackSerialize().Serialize(tracks);
            HttpStatusCode code = HttpHelper.PostJsonVoid(this._Config.PostUri, json);
            if (code != HttpStatusCode.OK)
            {
                new WarnLog("Trace.submit.error", "链路跟踪数据提交失败!", "Trace_Zipkin")
                                {
                                        { "StatusCode",code.ToString()},
                                        {"Uri",this._Config.PostUri },
                                        {"Trace",json }
                                }.Save();
            }
        }

        public void AddTrace (TrackBody track)
        {
            this._TackList.AddData(track);
        }

        public void Dispose ()
        {
            this._TackList.Dispose();
        }
    }
}
